//  widget.js

var widgetManagement = require('../base/deliverManagement'),
    widgetDeliver = require('../base/deliver'), 
    siteUtils = require('../base/siteUtils'),     
    crypto = require('../common/crypto'),
    excel = require('excel-export')
    ;

var method = '',
    params = null,
    user = null;

function generateWidget(params,type){
  var wt = params.widgetType,
      at = params.adType,
      width = params.adSize.split('x')[0],
      height = params.adSize.split('x')[1],
      w = {};

  //弹窗广告插件      
  if(wt == 1){
        w={
          width : width,
          height : height,              
          pubID : params.pubID.trim(),
          slot : params.slot.trim(),
          dfpID : params.dfpID.trim(),
          dfpName : params.dfpName.trim(),
          widgetStyle : params.widgetStyle||1,
          closePosition : params.closePosition||'',
          showLogo : parseInt(params.showLogo),
          showReplay : parseInt(params.showReplay),
          closeReplay : parseInt(params.closeReplay),
          minitime : params.minitime
        };
     }else if(wt == 2){  //固定位广告插件
        // 固定位插件banner类型广告
        if(at == 'banner'){
            w = {
                  width : params.width,
                  height : params.height,
                  pubID1 : params.pubID1.trim(),
                  slot1 : params.slot1.trim(),
                  w1 : params.adSize1.split('x')[0]||'',
                  h1 : params.adSize1.split('x')[1]||'',
                  pubID2 : params.pubID2.trim(),
                  slot2 : params.slot2.trim(),
                  w2 : params.adSize2.split('x')[0]||'',
                  h2 : params.adSize2.split('x')[1]||''
            };
          }else{
            w = {
              width : width,
              height : height,
              pubID : params.pubID.trim(),
              slot : params.slot.trim(),
              dfpID : params.dfpID.trim(),
              dfpName : params.dfpName.trim()
            }
          }
          w.showClose = parseInt(params.showClose);
          w.async = parseInt(params.async);  //是否使用异步代码 0否 1是
     }else if(wt == 3){ //对联广告插件
        w = {
          width : width,
          height : height,
          pubID1 : params.pubID1.trim(),
          pubID2 : params.pubID2.trim(),
          slot1 : params.slot1.trim() || '',
          slot2 : params.slot2.trim() || '',
          closePosition : params.closePosition || ''
        }
     }else if(wt == 4){ //底部横幅广告插件
       w={
          width : width,
          height : height,
          pubID : params.pubID.trim(),
          slot : params.slot.trim(),
          dfpID : params.dfpID.trim(),
          dfpName : params.dfpName.trim(),
          widgetStyle : {
            backColor:params.backColor||'',
            borderColor:params.borderColor||''
          }
       }
       if(at=='banner'){
          w.pubID1 = params.pubID1.trim();
          w.slot1 = params.slot1.trim();
          w.w1 = params.adSize1.split('x')[0]||'';
          w.h1 = params.adSize1.split('x')[1]||'';
          w.pubID2 = params.pubID2.trim();
          w.slot2 = params.slot2.trim();
          w.w2 = params.adSize2.split('x')[0]||'';
          w.h2 = params.adSize2.split('x')[1]||'';
       }
     }
     if(type == 'create'){
      w.siteField = params.siteField;
       w.sid = params.sid;
       w.siteName = params.siteName;
       w.widgetType = wt;
     }else if(type == 'edit'){
       w.field = params.field;
     }
     w.isAlive = params.isAlive;
     w.widgetName = params.widgetName;     
     w.adType = at;
     if(wt!=4){            
       w.fdfpID = typeof params.fdfpID!='undefined'?params.fdfpID.trim():'';
       w.fdfpName = typeof params.fdfpName!='undefined'?params.fdfpName.trim():''; 
     }
     w.adClickProb = (params.adClickProb||0)/100; 
     w.trackUrl =  params.trackUrl;
     return w;
};

var widget = {
	create : function(req,res){
    if(user.isAdmin){
        if(method=='GET'){
          var siteField =req.query.siteField,                      
              siteName = req.query.siteName,
              widgetType = req.query.widgetType;
          res.render('widget/create',{siteField : siteField,siteName : siteName,widgetType : widgetType});
        }else if(method=='POST'){              
          var siteField = params.siteField,
              sid =siteField.split(':')[0],
              siteName = params.siteName,
              widgetType = params.widgetType,
              widgetName = params.widgetName;
              params.sid = sid;
          if(widgetType>4||widgetType<1){
            res.render('widget/create',{err : '插件类型错误',siteField : siteField,siteName : siteName,widgetType : widgetType});  
          }else if(!siteField || !siteName){
            res.render('widget/create',{err : '必须选择一个网站',siteField : siteField,siteName : siteName,widgetType : widgetType});
          }else if(!widgetName){
            res.render('widget/create',{err : '插件名称不能空',siteField : siteField,siteName : siteName,widgetType : widgetType});
          }else{
            var obj = generateWidget(params,'create');                  
            widgetManagement.createDeliver(obj,function(result){
              if(result.err){
                res.render('widget/create',{err : result.err,sid : sid,siteName : siteName,widgetType : widgetType});
              }else{
                res.redirect('/site/details?field='+siteField);
              }
            });
          }
        }
      }else{
        res.send("sorry,you have no permission to this page");
    }
  },
 edit : function(req,res){
    if(user.isAdmin){
      if(method == 'GET'){
        var field = req.query.field;
        widgetManagement.deliverDetail(field,function (result) {
          var obj = result?JSON.parse(result) : null; 
          siteUtils.getSite(obj.siteField,function(result){ //to get the siteName
            if(result){
              obj.siteName = JSON.parse(result).siteName;
            }            
            res.render('widget/edit',{widget : obj});
          });          
        });
      }else if(method == 'POST'){
         var field = params.field;
         if(field){
           var obj = generateWidget(params,'edit'); 
           if(obj.adType == 'banner'){
              if(!obj.pubID1&&!obj.pubID2){
                res.render('widget/edit',{widget : obj,log:{type : 'error',message : '抱歉，你至少得创建一个banner广告'}});
                return false;
              }else if(!obj.width || !obj.height){
                res.render('widget/edit',{widget : obj,log:{type : 'error',message : '抱歉，banner广告位尺寸不能为0或空值'}});
                return false;
              }                    
           }
           obj.author = user.email; //for changelog 
           widgetManagement.editDeliver(obj,function(result){
              if(result.err){
                res.render('widget/edit',{widget : obj , err : result.err});
              }else{
                res.redirect('/site/details?field='+params.siteField);
              }
           });
             
         }else{
          res.send("cannot find the widget");
         }        
      }
    }else{
       res.send("sorry,you have no permission to this page");        
      }
 },
       delete : function(req,res){
          if(user.isAdmin){
            var field = req.param('field');
            widgetManagement.stopDeliver(field,function(result){
              if(result.err){
                res.send({err : result.err});
              }else{
                widgetManagement.delDeliver(field,user.email,function(result){
                  if(result.err){
                    res.send({err : result.err});
                  }else{
                    res.send({success : true});
                  }
                });
              }
            });
          }else{
             res.send("sorry,you have no permission to this page");        
          }
       },
       updateState : function(req,res){
          if(user.isAdmin){
            var field = req.param('field'),
                  state = req.param('state');

              var callback = function(result){
                  if(result.err){
                    res.send({err : result.err});
                  }else{
                    res.send({success : true});
                  }
              };

              if(state){
                widgetManagement.activeDeliver(field,function(result){
                  callback(res,result);
                });
              }else{
                widgetManagement.stopDeliver(field,function(result){
                  callback(res,result);
                })
              }
          }else{
            res.send("sorry,you have no permission to this page");        
          }
       },
       code : function(req,res){
          var wt = req.param('widgetType')
              ,field = req.param('field')
              ,title = req.param('title')||''
              ;
          res.render('widget/code',{field : field,widgetType : wt,title:title});
       },
       preview : function(req,res){
          var wt = req.param('widgetType'),
                wn = req.param('widgetName'),
                field = req.param('field');
          res.render('widget/preview',{field : field,widgetType : wt,widgetName : wn});
       },
       push : function(req,res){
           var config=res.locals.config;
           var field=req.param('field'),                 
                 url=decodeURIComponent(req.param('url')),
                 callback=req.param('callback');
           if(field&&url&&callback){
              widgetDeliver.deliver(field,url,function(result){
                if(result.err){
                  console.log(result.err)
                  res.send(callback+"()");                 
                }else{ 
                  var myDate = new Date();
                  var data=result;
                  var isNewUser = 0;
                  var cookie = req.cookies[config.deliverCookieName];
                  if(!cookie){
                    var maxAge= config.maxAge; 
                    var randNum = parseInt(63*Math.random());
                    var deliver_token = crypto.encrypt(myDate.getTime() + '\t' + '1' + '\t' + randNum, config.sessionSecret);
                    res.cookie(config.deliverCookieName, deliver_token, {path: '/',maxAge: maxAge});
                    cookie = deliver_token;
                    isNewUser = 1;
                  }                  
                  var ip = req.header('x-forwarded-for')||req.connection.remoteAddress
                  var logStr = '[istc_deliver_log]' + config.version + '\t' + myDate.getTime() + '\t' + '8' + '\t' + '13' + '\t' + 
            '\t' + '\t' + 'istc_deliver' + '\t' + isNewUser + '\t' + ip + '\t' + req.header('user-agent') + '\t' + 'zh-cn' + '\t' + 
            JSON.stringify(req.query) + '\t' + url + '\t' + '\t' + '\t' + '\t' + '\t' + field + '\t' + '\t' + '\t' + '\t' + '\t' + '\n';
                  widgetDeliver.record(cookie, config.deliverlog, logStr, function(res){
                    if(res){
                      console.log('deliverlog success!');
                    }else{
                      console.log('deliverlog failed!');
                    }
                  });
                  res.send(callback+"("+data+")");
                }
              });
           }else{
              res.send({err:'Cannot GET Ad'});
           }  
       },       
       permanent:function(req,res){
           var field = req.param('field')
               ,agent = req.get('user-agent')
               ,isIE = !!(agent.indexOf('MSIE')!=-1)
               ,isMobile = !!(agent.indexOf('Mobile')!=-1);
            if(field){              
              res.render('widget/permanent',{field:field,isIE:isIE,isMobile:isMobile}); 
            }else{
              res.send(''); 
            }                      
       },
       // 添加报表
       addReport: function(req,res){
        if(user.isAdmin){
          if(method=='GET'){
            var field = req.query.field
                ,title = req.query.title
                ,now = Date.now()
                ,dateArr = []
                ,count = 10
                ;
            for(var i = 0;i<count;i++){
              var d = new Date(new Date(now-24*60*60*1000*i).toDateString()).getTime();
              dateArr.push(d);
            }
            // 获取近7天的报表数据            
            widgetManagement.getReportData(field,dateArr,function(err,reply){
              var reportData = [];
              if(reply){
                reportData = reply;
              }
             
              widgetManagement.getReportSetting(field,function(err,reply){
                var setting = {

                };
                if(reply){
                  setting=JSON.parse(reply);
                }
                res.render('widget/report',{
                  field:field,
                  title:title,
                  setting:setting,
                  reportData:reportData
                });              
              });              
            })
          }else if(method=='POST'){
            var field = params.field
                ,title = params.title
                ,adRequest = parseInt(params.request)
                ,adView = parseInt(params.view)
                ,adClick = parseInt(params.click)
                ,adRevenue = parseFloat(params.revenue)
                ,date = new Date(params.date).toDateString()
                ,data = {
                  date:params.date,
                  title:title,
                  request:adRequest,
                  view:adView,
                  click:adClick,
                  revenue:adRevenue
                };
            widgetManagement.addReportData(field,new Date(date).getTime(),data,function(err,reply){
              if(err){
                res.send({err:err})
              }else{
                res.send({
                  result:data
                })
              }
            });
          }
        }else{
           res.send("sorry,you have no permission to this page");
        }
    },
    // 导出报表数据
    exportReport: function(req,res){
      if(method=='GET'){
        var field = req.query.field
            ,title = req.query.title||''
            ,from = req.query.date_from||''
            ,to = req.query.date_to||''
            ,dateArr = []
            ;  
        // 如果有传递时间
        if(from&&to){
          try{
            var from_time = new Date(new Date(from).toDateString()).getTime()
                ,to_time = new Date(new Date(to).toDateString()).getTime()
                ;
            for(var i = from_time;i<=to_time;){
              dateArr.push(i);
              i+=24*60*60*1000;
            } 
            // 查询数据           
            widgetManagement.getReportData(field,dateArr,function(err,reply){
              var reportData = [];
              if(reply){
                reportData = reply;
              }    
              res.render('widget/exportReport',{title:title,field:field,from:from,to:to,reportData:reportData});                 
            })          
          } catch(e){
            res.send('!!服务器出错了')
          }           
        }else{
          res.render('widget/exportReport',{title:title,field:field,from:from,to:to});
        }
      }else if(method=='POST'){
        var reportData = req.body.reportData;
        if(reportData&&reportData.length){
          var conf ={};
          conf.cols = [{
            caption:'日期',
            type:'string',
          },{
            caption:'请求次数',
            type:'number'
          },{
            caption:'曝光次数',
            type:'number'
          },{
            caption:'点击次数',
             type:'number'              
          },{
            caption:'收入(人民币)',
             type:'number'              
          }];
          conf.rows = JSON.parse(reportData);
          var result = excel.execute(conf);
          res.setHeader('Content-Type', 'application/vnd.openxmlformats');
          res.setHeader("Content-Disposition", "attachment; filename=" + "Report.xlsx");
          res.end(result, 'binary');          
        }
      }
    },
    // 生成昨日数据
    generateReportData: function(req,res){
      var field = req.param('field');
      widgetManagement.generateSingleReportData(field,function(err,reply){
        console.log(err,reply)
        if(err){
          res.send({err:err})
        }else{
          res.send({result:reply})
        }
      })
    },
    dataAPI:function(req,res){
      var field = req.param('field')
          ,date = req.param('date')
          ;

      if(field&&date){
        var dateArr = date.split(',');
        // 将date转换成时间戳
        dateArr.forEach(function(val,i){
          var d = new Date(val).toDateString();
          dateArr[i] = new Date(d).getTime();
        });
        widgetManagement.getReportData(field,dateArr,function(err,reply){
          if(err){
            res.send({err:'服务器出错了...'});
          }else{
            res.send({result:reply});
          }
        })
      }
    },
    setReportSetting: function(req,res){
      var field = req.param('field')
          ,title = req.param('title')
          ;
      try{
       var data = { 
          field:field,
          title:title,
          cnzzid : req.param('cnzzid'),
          maxpv : parseInt(req.param('maxpv')),
          cpm : parseFloat(req.param('cpm')),
          minAvailPer : parseFloat(req.param('minAvailPer')),
          minPercent : parseFloat(req.param('minPercent')),
          maxPercent : parseFloat(req.param('maxPercent'))
        }       
      }catch(err){
        res.send({err:err.message})
      }

      for(i in data){
        if(data[i]==undefined||data[i]==null){
          res.send({err:'数据不能为空'});
        }
      }

      if(field){
        widgetManagement.setReportSetting(field,data,function(err,reply){
          if(err){
            res.send({err:err});
          }else{
            res.send({result:reply})
          }
        });
      }else{
        res.send({err:'缺少参数'});
      }
    }
}

exports.index = function  (req,res) {
      var action=req.params.action;   
      var action_not_auth = ['push','permanent','dataAPI'];   
      if(action&&widget[action]){
        if(req.session.user||action_not_auth.indexOf(action)!=-1){
          method=req.method;
          params = req.body;
          user = req.session.user;
          widget[action](req,res);
        }else{
          res.redirect('/user/signin');
        }    
      }else{      
        res.send('Cannot GET  '+req.path);
      }	
}